/*
 * Copyright © 2011 Nokia Corporation. All rights reserved.
 * Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. 
 * Oracle and Java are trademarks or registered trademarks of Oracle and/or its
 * affiliates. Other product and company names mentioned herein may be trademarks
 * or trade names of their respective owners. 
 * See LICENSE.TXT for license information.
 */ 

package com.nokia.example.wordpress.views;

import com.nokia.example.wordpress.components.OptionsMenu;
import com.nokia.example.wordpress.helpers.KeyCodes;
import com.nokia.example.wordpress.networking.Blog;
import com.nokia.example.wordpress.networking.GetRecentPostsOperation;
import com.nokia.example.wordpress.networking.NewPostOperation;
import com.nokia.mid.ui.TextEditor;
import com.nokia.mid.ui.TextEditorListener;
import java.util.Vector;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.TextField;

/**
 * View for writing a new post.
 */
public class NewPostView extends BaseView implements TextEditorListener {

    private TextEditor titleEditor;
    private TextEditor contentEditor;

    NewPostView(Graphics g, int x, int y, int width, int height) {
        super(g, ViewMaster.VIEW_NEWPOST, x, y, width, height);
        haveTabs = false;

        int border = 2;
        int editorWidth = width - 2 * border;

        titleEditor = TextEditor.createTextEditor(100/*max char len*/, TextField.ANY, editorWidth, 1/*rows*/);
        titleEditor.setFont(Visual.SMALL_FONT);
        titleEditor.setBackgroundColor(Visual.EDITOR_ACTIVE_BACKGROUND_COLOR); // white
        titleEditor.setForegroundColor(Visual.EDITOR_ACTIVE_FOREGROUND_COLOR); // black
        titleEditor.setContent("");
        titleEditor.setParent(viewMaster);
        titleEditor.setPosition(border, Visual.SMALL_FONT.getHeight());
        titleEditor.setVisible(false);
        titleEditor.setTextEditorListener(this);

        int rowsLeft = 6; // this is suitable for the C3

        contentEditor = TextEditor.createTextEditor(1000/*max char len*/, TextField.ANY, editorWidth, rowsLeft);
        contentEditor.setFont(Visual.SMALL_FONT);
        contentEditor.setBackgroundColor(Visual.EDITOR_PASSIVE_BACKGROUND_COLOR); // white
        contentEditor.setForegroundColor(Visual.EDITOR_PASSIVE_FOREGROUND_COLOR); // black
        contentEditor.setContent("");
        contentEditor.setParent(viewMaster);
        contentEditor.setPosition(border, Visual.SMALL_FONT.getHeight() + titleEditor.getPositionY() + titleEditor.getHeight());
        contentEditor.setVisible(false);
        contentEditor.setTextEditorListener(this);


        // Create options menu
        menu = new OptionsMenu(width, height) {

            {
                addExitItem();
            }
        };

        softkey1Label = "Options";
        softkey2Label = "Ok";
        softkey3Label = "Cancel";
    }

    public void activate() {
        System.out.println("newpost activate");
        super.activate();
        titleEditor.setContent("");
        contentEditor.setContent("");
    }

    public void deactivate() {
        System.out.println("newpost deactivate");
        titleEditor.setVisible(false);
        contentEditor.setVisible(false);
    }

    public void transitionFinished()
    {
        titleEditor.setVisible(true);
        titleEditor.setFocus(true);
        contentEditor.setVisible(true);
    }

    public void draw(int x, int y, int width, int height) {
        System.out.println("newpost render");
        if (menu.isVisible()) {
            menu.draw(g);
            return;
        }
        //drawTabs();
        viewMaster.drawBackground(g, x, y, width, height, false);

        g.setColor(Visual.LIST_PRIMARY_COLOR);
        g.setFont(Visual.SMALL_FONT);
        g.drawString("Post title:", titleEditor.getPositionX() + titleEditor.getWidth() / 2, titleEditor.getPositionY() - Visual.SMALL_FONT.getHeight(), g.TOP | g.HCENTER);
        g.drawString("Post content:", contentEditor.getPositionX() + contentEditor.getWidth() / 2, contentEditor.getPositionY() - Visual.SMALL_FONT.getHeight(), g.TOP | g.HCENTER);
        drawSoftkeys();
    }

    public void keyPressed(int keyCode) {

        if (menu != null && menu.notifyKeyEvents(keyCode)) {
            // menu used this keycode, let's not use for anything else.
            viewMaster.draw();
            return;
        }

        switch (keyCode) {
            case KeyCodes.MIDDLE_SOFTKEY:
                // Ok, send post
                sendPost();
                break;
            case KeyCodes.RIGHT_SOFTKEY:
                // Cancel
                viewMaster.setPreviousView();
                return;
            default:
                break;

        }
    }

    public void inputAction(TextEditor editor, int actions) {
        if ((actions & TextEditorListener.ACTION_CARET_MOVE) != 0) {
            // Caret was moved. Calculate for example a new position
            // for a custom scroll bar using layout metrics.
        }
        if ((actions & TextEditorListener.ACTION_TRAVERSE_NEXT) != 0) {
            titleEditor.setFocus(false);
            contentEditor.setFocus(true);

            contentEditor.setBackgroundColor(Visual.EDITOR_ACTIVE_BACKGROUND_COLOR);
            contentEditor.setForegroundColor(Visual.EDITOR_ACTIVE_FOREGROUND_COLOR);

            titleEditor.setBackgroundColor(Visual.EDITOR_PASSIVE_BACKGROUND_COLOR);
            titleEditor.setForegroundColor(Visual.EDITOR_PASSIVE_FOREGROUND_COLOR);

        }
        if ((actions & TextEditorListener.ACTION_TRAVERSE_PREVIOUS) != 0) {
            titleEditor.setFocus(true);
            contentEditor.setFocus(false);

            contentEditor.setBackgroundColor(Visual.EDITOR_PASSIVE_BACKGROUND_COLOR);
            contentEditor.setForegroundColor(Visual.EDITOR_PASSIVE_FOREGROUND_COLOR);

            titleEditor.setBackgroundColor(Visual.EDITOR_ACTIVE_BACKGROUND_COLOR);
            titleEditor.setForegroundColor(Visual.EDITOR_ACTIVE_FOREGROUND_COLOR);
        }
    }

    /**
     * Sends the post to the server.
     */
    private void sendPost() {
        titleEditor.setFocus(false);
        contentEditor.setFocus(false);
        viewMaster.drawDimmedBackground();
        busy = true; // this will trigger busy animation

        final NewPostOperation.Listener postListener = new NewPostOperation.Listener() {

            // After post sent, get the posts from the server.
            // This could be done more efficiently by adding the new post manually
            // to the posts vector and reloading in background.
            public void newPostSent(Blog blog, String postId) {
                System.out.println("post sent");
                getPosts();
            }
        };

        NewPostOperation op = new NewPostOperation(postListener, data.getBlog(), titleEditor.getContent(), contentEditor.getContent());
        op.start();
    }

    /**
     * Loads posts from the server,
     */
    private void getPosts() {
        final GetRecentPostsOperation.Listener postsListener = new GetRecentPostsOperation.Listener() {

            // After receiving the posts, store them and enter the posts view.
            public void postsReceived(Vector posts) {
                System.out.println("posts received");
                data.setPosts(posts);
                viewMaster.setView(ViewMaster.VIEW_POSTS);
            }
        };
        GetRecentPostsOperation op = new GetRecentPostsOperation(postsListener, data.getBlog());
        op.start();
    }

}
